package com.slz.crm.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slz.crm.common.exiception.BaseException;
import com.slz.crm.common.untils.BaseUnit;
import com.slz.crm.pojo.dto.BusinessActivityDTO;
import com.slz.crm.pojo.dto.BusinessActivityQueryDTO;
import com.slz.crm.pojo.dto.BusinessActivityUserDTO;
import com.slz.crm.pojo.entity.*;
import com.slz.crm.pojo.vo.BusinessActivityVO;
import com.slz.crm.server.constant.MessageConstant;
import com.slz.crm.server.mapper.*;
import com.slz.crm.server.service.BusinessActivityService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class BusinessActivityServiceImpl extends ServiceImpl<BusinessActivityMapper, BusinessActivityEntity> implements BusinessActivityService {

    @Autowired
    private BusinessActivityMapper businessActivityMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CustomerCompanyMapper customerCompanyMapper;
    @Autowired
    private SalesOpportunityMapper salesOpportunityMapper;
    @Autowired
    private BusinessActivityContactMapper businessActivityContactMapper;
    @Autowired
    private BusinessActivityUserMapper businessActivityUserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean create(BusinessActivityDTO businessActivityDTO) {

        BusinessActivityEntity businessActivityEntity = new BusinessActivityEntity();
        BeanUtils.copyProperties(businessActivityDTO, businessActivityEntity);

        Long currentId = BaseUnit.getCurrentId();

        businessActivityEntity.setCreatorId(currentId);
        save(businessActivityEntity);

        //插入联系人活动关联
        List<BusinessActivityUserDTO> userIdList = businessActivityDTO.getUserIdList();
        List<BusinessActivityUserDTO> contactIdList = businessActivityDTO.getContactIdList();

        contactIdList.forEach(contactId -> {
            BusinessActivityContactEntity entity = new BusinessActivityContactEntity();
            BeanUtils.copyProperties(contactId, entity);

            entity.setCreatorId(currentId);
            entity.setActivityId(businessActivityEntity.getId());
            businessActivityContactMapper.insert(entity);
        });


        //插入用户活动关啦
        userIdList.forEach(contactId -> {
            BusinessActivityUserEntity entity = new BusinessActivityUserEntity();
            BeanUtils.copyProperties(contactId, entity);
            entity.setCreatorId(currentId);
            entity.setActivityId(businessActivityEntity.getId());
            businessActivityUserMapper.insert(entity);
        });

        return true;
    }

    @Override
    public Page<BusinessActivityVO> businessActivityQuery(Integer pageNum, Integer pageSize, BusinessActivityQueryDTO dto) {
        Page<BusinessActivityEntity> page = new Page<>(pageNum, pageSize);

        Page<BusinessActivityEntity> entityPage = businessActivityMapper.selectPage(
                page,
                getQueryWrapper(dto)
        );

        // 转换为VO
        Page<BusinessActivityVO> voPage = new Page<>();
        BeanUtils.copyProperties(entityPage, voPage);

        List<BusinessActivityVO> voList = entityPage.getRecords().stream()
                .map(entity -> {
                    String[] names = getBusinessActivityNames(entity);
                    return BusinessActivityVO.fromEntity(entity, names[0], names[1], names[2]);
                })
                .toList();

        voPage.setRecords(voList);
        return voPage;
    }


    /**
     * 构建查询包装器
     *
     * @param queryDTO 查询条件
     * @return 查询包装器
     */
    public LambdaQueryWrapper<BusinessActivityEntity> getQueryWrapper(BusinessActivityQueryDTO queryDTO) {
        LambdaQueryWrapper<BusinessActivityEntity> queryWrapper = new LambdaQueryWrapper<>();

        // 按活动标题查询
        if (queryDTO.getActivityTitle() != null && !queryDTO.getActivityTitle().isEmpty()) {
            queryWrapper.like(BusinessActivityEntity::getActivityTitle, queryDTO.getActivityTitle());
        }
        // 按活动类型查询
        if (queryDTO.getActivityType() != null && !queryDTO.getActivityType().isEmpty()) {
            queryWrapper.eq(BusinessActivityEntity::getActivityType, queryDTO.getActivityType());
        }
        // 按活动内容查询
        if (queryDTO.getActivityContent() != null && !queryDTO.getActivityContent().isEmpty()) {
            queryWrapper.like(BusinessActivityEntity::getActivityContent, queryDTO.getActivityContent());
        }
        //公司名称模糊搜索
        if (queryDTO.getCompanyName() != null && !queryDTO.getCompanyName().isEmpty()) {
            Set<Long> companyIds = customerCompanyMapper.selectCompanyIdsByName(queryDTO.getCompanyName());
            if (!companyIds.isEmpty()) {
                queryWrapper.in(BusinessActivityEntity::getCompanyId, companyIds);
            } else {
                queryWrapper.eq(BusinessActivityEntity::getCompanyId, -1);
            }
        }
        //创建人名称模糊搜索
        if (queryDTO.getCreatorName() != null && !queryDTO.getCreatorName().isEmpty()) {
            Set<Long> creatorIds = userMapper.selectUserIdsByUserName(queryDTO.getCreatorName());
            if (!creatorIds.isEmpty()) {
                queryWrapper.in(BusinessActivityEntity::getCreatorId, creatorIds);
            } else {
                queryWrapper.eq(BusinessActivityEntity::getCreatorId, -1);
            }
        }
        //销售机会名称模糊搜索
        if (queryDTO.getOpportunityName() != null && !queryDTO.getOpportunityName().isEmpty()) {
            Set<Long> opportunityIds = salesOpportunityMapper.selectOpportunityIdsByName(queryDTO.getOpportunityName());
            if (!opportunityIds.isEmpty()) {
                queryWrapper.in(BusinessActivityEntity::getOpportunityId, opportunityIds);
            } else {
                queryWrapper.eq(BusinessActivityEntity::getOpportunityId, -1);
            }
        }
        // 备注模糊搜索
        if (queryDTO.getRemark() != null && !queryDTO.getRemark().isEmpty()) {
            queryWrapper.like(BusinessActivityEntity::getRemark, queryDTO.getRemark());
        }
        // 创建时间范围搜索
        if (queryDTO.getMinCreateTime() != null && queryDTO.getMaxCreateTime() != null) {
            queryWrapper.between(BusinessActivityEntity::getCreateTime, queryDTO.getMinCreateTime(), queryDTO.getMaxCreateTime());
        }
        // 活动日期范围搜索
        if (queryDTO.getMinActivityTime() != null && queryDTO.getMaxActivityTime() != null) {
            queryWrapper.between(BusinessActivityEntity::getActivityTime, queryDTO.getMinActivityTime(), queryDTO.getMaxActivityTime());
        }
        // 活动时长搜索
        if (queryDTO.getActivityDuration() != null) {
            queryWrapper.eq(BusinessActivityEntity::getActivityDuration, queryDTO.getActivityDuration());
        }

        // 默认按创建时间倒序
        queryWrapper.orderByDesc(BusinessActivityEntity::getCreateTime);

        return queryWrapper;

    }


    /**
     * 获取商业活动相关的公司名称、创建者名称和销售机会名称
     *
     * @param entity 商业活动实体
     * @return 包含公司名称、创建者名称和销售机会名称的数组，顺序为：[companyName, creatorName, opportunityName]
     */
    private String[] getBusinessActivityNames(BusinessActivityEntity entity) {
        String companyName = null;
        String creatorName = null;
        String opportunityName = null;

        // 公司名称
        if (entity.getCompanyId() != null) {
            CustomerCompanyEntity companyEntity = customerCompanyMapper.selectById(entity.getCompanyId());
            if (companyEntity != null) {
                companyName = companyEntity.getCompanyName();
            }
        }

        // 创建者名称
        if (entity.getCreatorId() != null) {
            UserEntity userEntity = userMapper.selectById(entity.getCreatorId());
            if (userEntity != null) {
                creatorName = userEntity.getRealName();
            }
        }

        // 销售机会名称
        if (entity.getOpportunityId() != null) {
            SalesOpportunityEntity opportunityEntity = salesOpportunityMapper.selectById(entity.getOpportunityId());
            if (opportunityEntity != null) {
                opportunityName = opportunityEntity.getOpportunityName();
            }
        }

        return new String[]{companyName, creatorName, opportunityName};
    }


    /**
     * 获取名称
     *
     * @param vo 商业活动VO
     */
    public void getName(BusinessActivityVO vo) {
        //获取公司名称
        if (vo.getCompanyId() != null) {
            CustomerCompanyEntity companyEntity = customerCompanyMapper.selectById(vo.getCompanyId());
            if (companyEntity != null) {
                vo.setCompanyName(companyEntity.getCompanyName());
            }
        }
        //获取销售机会名称
        if (vo.getOpportunityId() != null) {
            SalesOpportunityEntity opportunityEntity = salesOpportunityMapper.selectById(vo.getOpportunityId());
            if (opportunityEntity != null) {
                vo.setOpportunityName(opportunityEntity.getOpportunityName());
            }
        }
        //获取创建人名称
        if (vo.getCreatorId() != null) {
            UserEntity userEntity = userMapper.selectById(vo.getCreatorId());
            if (userEntity != null) {
                vo.setCreatorName(userEntity.getRealName());
            }
        }

    }


    @Override
    public List<BusinessActivityVO> getAllActivity(Integer pageNum, Integer pageSize) {

        List<BusinessActivityVO> ans = new ArrayList<>();

        Page<BusinessActivityEntity> page = new Page<>(pageNum, pageSize);
        Page<BusinessActivityEntity> pageResult = page(page, new LambdaQueryWrapper<>());

        for (BusinessActivityEntity businessActivityEntity : pageResult.getRecords()) {
            String[] names = getBusinessActivityNames(businessActivityEntity);
            BusinessActivityVO businessActivityVO = BusinessActivityVO.fromEntity(businessActivityEntity, names[0], names[1], names[2]);
            ans.add(businessActivityVO);
        }

        return ans;
    }

    @Override
    public BusinessActivityVO getDetailById(Long id) {
        // 参数校验
        if (id == null) {
            throw new BaseException(MessageConstant.PARAM_ERROR);
        }

        BusinessActivityEntity entity = getById(id);
        if (entity == null) {
            throw new BaseException(MessageConstant.BUSINESS_ACTIVITY_IS_NOT_EXIST);
        }

        String[] names = getBusinessActivityNames(entity);
        return BusinessActivityVO.fromEntity(entity, names[0], names[1], names[2]);
    }

    @Override
    @Transactional
    public Integer updateList(List<BusinessActivityDTO> businessActivityDTOList) {

        List<BusinessActivityEntity> businessActivityEntityList = new ArrayList<>();

        for (BusinessActivityDTO businessActivityDTO : businessActivityDTOList) {
            BusinessActivityEntity businessActivityEntity = new BusinessActivityEntity();
            BeanUtils.copyProperties(businessActivityDTO, businessActivityEntity);
            businessActivityEntityList.add(businessActivityEntity);
        }

        updateBatchById(businessActivityEntityList);

        return businessActivityEntityList.size();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer deleteByIds(List<Long> idList) {
        if (idList == null || idList.isEmpty()) {
            throw new BaseException(MessageConstant.ID_LIST_IS_NULL);
        }

        // 2. 物理删除活动本身
        return businessActivityMapper.deleteBatchIds(idList);
    }
}
